<?php 
define('JASON_SHOP', '8b718382d40f4bbab531aeb1521e2aca');


// 用来生成客户的邀请码
function shorturl($input) {
	$base32 = array (
	'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
	'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
	'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
	'y', 'z', '0', '1', '2', '3', '4', '5'
	);
	$hex = md5($input);
	$hexLen = strlen($hex);
	$subHexLen = $hexLen / 8;
	$output = array();
	for ($i = 0; $i < $subHexLen; $i++) {
	//把加密字符按照8位一组16进制与0x3FFFFFFF(30位1)进行位与运算
	$subHex = substr ($hex, $i * 8, 8);
	$int = 0x3FFFFFFF & (1 * ('0x'.$subHex));
	$out = '';
	for ($j = 0; $j < 6; $j++) {
	//把得到的值与0x0000001F进行位与运算，取得字符数组chars索引
	$val = 0x0000001F & $int;
	$out .= $base32[$val];
	$int = $int >> 5;
	}
	$output[] = $out;
	}
	return $output;
}





function getUserLevel($user){
	// $level = C("level");
	// p($level);
}
function get_status_txt($status,$order_status){
	if($status==1) $txt = "挂单中";
	if($status==2){
		$txt = "交易中";
		if($order_status==1) $txt = "待付款";
		if($order_status==2) $txt = "待确认";
		if($order_status==3) $txt = "交易完成";
	}
	if($status==3) $txt = "交易完成";
	return $txt;
}
function get_order_code($fix=''){
	return $fix.time().substr(microtime(),2,6).rand(0,9);
}
/**
 * 判断夺宝时间是否在 时时彩规定的开奖时间段 9:50-22:00 22:00-01:55
 * @param 	unknown $orderTime 		 订单时间
 * @return 	boolean
 */
function time_sel($orderTime){
	$hour = date('H',$orderTime);
	$time = $orderTime;
	if($hour >=0 && $hour <=2 ){
		$statr_int_time = strtotime(date('Y-m-d',$time).'00:00:00');
		$end_int_time = strtotime(date('Y-m-d',$time).'01:55:00');
		if($time >= $statr_int_time && $time <= $end_int_time){
			return true;
		}else{
			return false;
		}
	}else{
		$statr_int_time = strtotime(date('Y-m-d',$time).'09:50:00');
		$end_int_time = strtotime(date('Y-m-d',strtotime("+1 day",$time)).'00:00:00');
		if($time >= $statr_int_time && $time <= $end_int_time){
			return true;
		}else{
			return false;
		}
	}
}
/**
 * 判断开奖时间段是白天还是晚上
 * @param 	unknown $time  订单时间
 */
function open_is_day($time){
	$hour = date('H',$time);
	/* $day_int_time = strtotime(date('Y-m-d',$time).'09:50:00');
	$day_end_time = strtotime(date('Y-m-d',$time).'22:00:00');
	$black_end_time = strtotime(date('Y-m-d',strtotime("+1 day",$time)).'01:55:00'); */
	if($hour >= 2 && $hour <= 22){
		return 'DAY';
	}else{
		return 'NIGHT';
	}
}
/**
 * 根据最后一个夺宝时间获取揭晓时间
 * @param unknown $timeArry
 */
function get_bless_time($ordertime){
	if(time_sel($ordertime)){//在时时彩开奖时间段
		if(open_is_day($ordertime) == 'DAY'){ 
	 		$int_time = intval(10);
	 		$minute = date('i',$ordertime);
	 		$yushu = $minute%10;
			$derfe = bcsub($int_time, $yushu);
			$addTime = bcadd($derfe, intval(3));
	 		$jx_time = bcadd($ordertime,$addTime*60);
	 		$format_time = strtotime(date('Y-m-d H:i',$jx_time).':00');
		}
		if(open_is_day($ordertime) == 'NIGHT'){
			$int_time = intval(5);
			$minute = date('i',$ordertime);
			$yushu = $minute%5;
			$derfe = bcsub($int_time, $yushu);
			$addTime = bcadd($derfe, intval(3));
			$jx_time = bcadd($ordertime,$addTime*60);
			$format_time = strtotime(date('Y-m-d H:i',$jx_time).':00');
		}
	}else{//不再开奖时间段揭晓时间
		$format_time = strtotime(date('Y-m-d',$ordertime).'10:03:00');
	}
	return $format_time;
}
function hour_time_show(){
	if(time_sel(time())){
		return false;
	}else{
		$bj_time = strtotime(date('Y-m-d',time()).'09:03:0');
		if(time() > $bj_time){
			return false;
		}else{
			return true;
		}
	}
}
function get_qishu_number($end_time){
	 $new_end_time = $end_time-(60*3);
	 $j_hour = intval(date('H',$new_end_time));
	// echo date('Y-m-d H:i:s',$new_end_time);exit;
	/* //echo date('Y-m-d H:i:s',$new_end_time);exit;
	$day_hour = '2';
	$day_end_hour = '22';
	//$black_end_time = strtotime(date('Y-m-d',strtotime("+1 day",$end_time)).'01:58:00');
	if($end_time >= $day_int_time && $end_time <= $day_end_time){//10分钟一期
		//echo 'ok';exit;
		$day_start = strtotime(date('Y-m-d',$end_time).'10:00:00');//白天第一期揭晓时间
		$day_start_qishu = date('Ymd',$end_time).'024';//白天第一期揭晓期数
		$bsApi = (bcsub($new_end_time, $day_start))/60/10;
		return  $bsApi+$day_start_qishu;
	}else if($end_time >= $day_end_time && $end_time <= $black_end_time ){//5分钟一期
		//echo 'false';exit;
		$int = 97;
		$night_start = strtotime(date('Y-m-d',$end_time).'22:05:00');//白天第一期揭晓时间
		$night_start_qishu = date('Ymd',$end_time).'097';//白天第一期揭晓期数
		$bsApi = (bcsub($new_end_time, $night_start))/60/5;
		$qishu = $bsApi+$night_start_qishu;
		$total = bcadd($int, $bsApi);
		if($total > 120){
			return date('Ymd',$end_time).bcsub($total,120);
		}else{
			return $qishu;
		}  
	} */
	 if($j_hour >= 2 && $j_hour <= 22){//10分钟一期
	 	$day_start = strtotime(date('Y-m-d',$end_time).'10:00:00');//白天第一期揭晓时间
	 	$day_start_qishu = date('Ymd',$end_time).'024';//白天第一期揭晓期数
	 	$bsApi = (bcsub($new_end_time, $day_start))/60/10;
	 	return  $bsApi+$day_start_qishu;
	 }else{//5分钟一期
	 	$int = 97;
	 	if(!$j_hour || $j_hour <= 2){
	 		$night_start = strtotime(date('Y-m-d',strtotime("-1 day",$end_time)).'22:05:00');
	 		$night_start_qishu = date('Ymd',strtotime("-1 day",$end_time)).'097';//夜晚第一期揭晓期数
	 	}else{
	 		$night_start = strtotime(date('Y-m-d',$end_time).'22:05:00');//白天第一期揭晓时间
	 		$night_start_qishu = date('Ymd',$end_time).'097';//夜晚第一期揭晓期数
	 	}
	 	//echo $night_start_qishu.'</br>';
	 	$bsApi = (bcsub($new_end_time, $night_start))/60/5;
	 	$qishu = $bsApi+$night_start_qishu;
	 	$total = bcadd($int, $bsApi);
	 	if($total > 120){
	 		$number = bcsub($total,120);
	 		if(strlen($number) == 1){
	 			$new_api = '00'.$number;
	 		}else if(strlen($number) == 2){
	 			$new_api = '0'.$number;
	 		}else{
	 			$new_api = $number;
	 		}
	 		return date('Ymd',$end_time).$new_api;
	 	}else{
	 		return $qishu;
	 	}
	 }
}
 /**
  * 得到会员头像
  * @param unknown $path
  * @return string
  */
 function get_avatar($path){
 	if(empty($path)){
 		$avater = '/statics/images/avatar.png';
 	}else{
 		$file_path = DOC_ROOT.$path;
 		if(!file_exists($file_path)){
 			$avater = '/statics/images/avatar.png';
 		}else{
 			$avater = $path;
 		}
 	}
 	return $avater."?v=1";
 }
function getImgs($content,$order='ALL'){
	$pattern="/<img.*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/";
	preg_match_all($pattern,$content,$match);
	if(isset($match[1])&&!empty($match[1])){
		if($order==='ALL'){
			return $match[1];
		}
		if(is_numeric($order)&&isset($match[1][$order])){
			return $match[1][$order];
		}
	}
	return '';
}
function money($num){
	$p= stripos($num, '.'); 
	return substr($num,0,$p+3);	
}
function now_collect_re($time,$uid,$allrebate){
	$map['user_id'] = array('EQ',$uid);
	$map['type'] = array('EQ',1);
	$map["add_time"]=array('between',array(strtotime(date("Y-m-d", $time) . " 00:00:01") ,strtotime(date("Y-m-d", $time) . " 23:59:59")));
	$num=M("user_rebate_log")->where($map)->sum("save_num");
	return $num==0?0:$num;
	if($num>0)return $allrebate-$num;
	else return $allrebate;
	//return $num==0?$allrebate:$num;
}
function now_collect($time,$uid){
	$map['user_id'] = array('EQ',$uid);
	$map['type']=9;
	//$time=time();
	$map["dateline"]= array('between',array(strtotime(date("Y-m-d", $time) . " 00:00:01") ,strtotime(date("Y-m-d", $time) . " 23:59:59")));
	$money=M("user_moneylog")->where($map)->sum("money");
	return $money==""?0:$money;
}
function allow_doamin(){
	$is_allow=false;
	$url=trim($_SERVER['SERVER_NAME']);
	$arr_allow_domain=array("www.51ttlg.com","51ttlg.com","101.201.145.16");
	foreach($arr_allow_domain as $value){
		$value=trim($value);
		$tmparr=explode($value,$url);
		if(count($tmparr)>1){
			$is_allow=true;
			break;
		}
	}
	if(strpos($_SERVER['SERVER_NAME'],"192.")===false)
	{
		if(!$is_allow){
			die("1");
		}
	}
}
//allow_doamin();
/**
 * 系统公共库文件
 * 主要定义系统公共函数库
 */
function hidecard($cardnum, $type = 1, $default = '')
{
    if (empty($cardnum)) {
        return $default;
    }
    if ($type == 1) {
        $cardnum = substr($cardnum, 0, 3) . str_repeat('*', 12) . substr($cardnum, strlen($cardnum) - 4);
    } else {
        if ($type == 2) {
            $cardnum = substr($cardnum, 0, 3) . str_repeat('*', 5) . substr($cardnum, strlen($cardnum) - 4);
        } else {
            if ($type == 3) {
                $cardnum = str_repeat('*', strlen($cardnum) - 4) . substr($cardnum, strlen($cardnum) - 4);
            } else {
                if ($type == 4) {
                    $cardnum = substr($cardnum, 0, 3) . str_repeat('*', strlen($cardnum) - 3);
                } else {
                    if ($type == 5) {
                        if (strlen($cardnum) == 6) {
                            $cardnum = mb_substr($cardnum, 0, 1, 'utf-8') . str_repeat('*', 2) . mb_substr($cardnum, -1, 0, 'utf-8');
                        } else {
                            $cardnum = mb_substr($cardnum, 0, 1, 'utf-8') . str_repeat('*', 2) . mb_substr($cardnum, -1, 1, 'utf-8');
                        }
                    }
                }
            }
        }
    }
    //$cardnum=iconv("UTF-8", "GBK", $cardnum);
    return $cardnum;
}
function hidemobi($phone){
    $IsWhat = preg_match('/(0[0-9]{2,3}[\-]?[2-9][0-9]{6,7}[\-]?[0-9]?)/i',$phone); //固定电话
    if($IsWhat == 1){
        return preg_replace('/(0[0-9]{2,3}[\-]?[2-9])[0-9]{3,4}([0-9]{3}[\-]?[0-9]?)/i','$1****$2',$phone);
    }else{
        return  preg_replace('/(1[358]{1}[0-9])[0-9]{4}([0-9]{4})/i','$1****$2',$phone);
    }
}
function object_array($array)
{
   if(is_object($array))
   {
    $array = (array)$array;
   }
   if(is_array($array))
   {
    foreach($array as $key=>$value)
    {
     $array[$key] = object_array($value);
    }
   }
   return $array;
}
/**
 * 获取缓存
 * @param  string $file 文件名
 * @param  string $dir  目录名
 * @return mixed
 */
function getcache($file, $dir = NULL) {
	 $fileName = (!is_null($dir) ? 'caches_'.$dir.'/'.$file : $file);
	 return F($fileName);
}
/**
 * 设置缓存
 * @param  string	$file	缓存名
 * @param  mixed	 $value  缓存值
 * @param  string	$dir	 目录名
 * @return mixed
 */
function setcache($file, $value = NULL, $dir = NULL) {
	 $fileName = (!is_null($dir) ? 'caches_'.$dir.'/'.$file : $file);
	 return F($fileName, $value);
}
/* 删除缓存文件 */
function delcache($file, $dir = NULL) {
	 $fileName = (!is_null($dir) ? 'caches_'.$dir.'/'.$file : $file);
	 return F($fileName, NULL);
}


function daddslashes($string, $force = 1) {
	 if(is_array($string)) {
		  $keys = array_keys($string);//返回包含数组中所有键名的一个新数组
		  foreach($keys as $key) {
				$val = $string[$key];
				unset($string[$key]);
				$string[addslashes($key)] = daddslashes($val, $force);
		  }
	 } else {
		  $string = addslashes($string);
	 }
	 return $string;
}



function dstripslashes($string) {
	if(empty($string)) return $string;
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = dstripslashes($val);
		}
	} else {
		$string = stripslashes($string);
	}
	return $string;
}
function dhtmlspecialchars($string, $flags = null) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = dhtmlspecialchars($val, $flags);
		}
	} else {
		if($flags === null) {
			$string = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string);
			if(strpos($string, '&amp;#') !== false) {
				$string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4}));)/', '&\\1', $string);
			}
		} else {
			if(PHP_VERSION < '5.4.0') {
				$string = htmlspecialchars($string, $flags);
			} else {
				if(strtolower(CHARSET) == 'utf-8') {
					$charset = 'UTF-8';
				} else {
					$charset = 'ISO-8859-1';
				}
				$string = htmlspecialchars($string, $flags, $charset);
			}
		}
	}
	return $string;
}
	function ClearHtml($str)
	{
		$str = strip_tags($str);
		//首先去掉头尾空格
		$str = trim($str);
		//接着去掉两个空格以上的
		$str = preg_replace('/\s(?=\s)/', '', $str);
		//最后将非空格替换为一个空格
		$str = preg_replace('/[\n\r\t]/', ' ', $str);
		return $str;
	}
/**
 * 获取跳转地址
 */
function dreferer($default = '') {
	 $referer = !empty($_GET['referer']) ? $_GET['referer'] : $_SERVER['HTTP_REFERER'];
	 $referer = substr($referer, -1) == '?' ? substr($referer, 0, -1) : $referer;
	 return $referer;
}
/**
 * 随机字符串
 *
 * @return bool
 **/
function random($length, $numeric = 0) {
	 $seed = base_convert(md5(microtime().$_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
	 $seed = $numeric ? (str_replace('0', '', $seed).'012340567890') : ($seed.'zZ'.strtoupper($seed));
	 if($numeric) {
		  $hash = '';
	 } else {
		  $hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
		  $length--;
	 }
	 $max = strlen($seed) - 1;
	 for($i = 0; $i < $length; $i++) {
		  $hash .= $seed{mt_rand(0, $max)};
	 }
	 return $hash;
}
/**
 * 获取类库地址
 * @param  [type] $libname [description]
 * @param  string $folder  [description]
 * @return [type]			 [description]
 */
function libfile($libname, $folder = '', $suffix = '.class.php', $import = TRUE) {
    $libpath = EXTEND_PATH.$folder;//Framework/Extend/$folder
    if(strstr($libname, '/')) {
        list($pre, $name) = explode('/', $libname);
        $path = "{$libpath}{$pre}/{$pre}_{$name}";
    } else {
        $path = "{$libpath}{$libname}";//{/Framework/Extend/}{Wechat}
	}
	///{/Framework/Extend/}{Wechat}.calss.php
    $result = (file_exists($path.$suffix)) ? realpath($path.$suffix) : false;
    if ($result == TRUE && $import === TRUE) {
        require_cache($path.$suffix);
    }
    return $result;
}
/**
 * JS动态加载
 */
function jsfile($name){
	libfile('jspack');
	$js = new jspack();
	return $js->import(JS_PATH,$name);
}
/**
 * 函数钩子
 * @return [type] [description]
 */
function runhook($hookid, $param, $type = 'string') {
	 libfile('hook');
	 $hook =  new hook();
	 return $hook->run($hookid, $param, $type);
}
/**
 * 生成SEO
 * @param $catid		  栏目ID
 * @param $title		  标题
 * @param $description  描述
 * @param $keyword		关键词
 */
function seo($catid = '', $title = '', $description = '', $keyword = '') {
	if (!empty($title))$title = strip_tags($title);
	if (!empty($description)) $description = strip_tags($description);
	if (!empty($keyword)) $keyword = str_replace(' ', ',', strip_tags($keyword));
	$cat = array();
	if (!empty($catid)) {
		$categorys = getcache('goods_category', 'goods');
		$cat = $categorys[$catid];
	}	
	$site_title = getconfig('site_name');
	$site_subtitle = getconfig('site_subtitle');
	$site_description = getconfig('site_description');
	if($site_subtitle) {
		$site_title .= ' - '.$site_subtitle;
	}
	$seo['site_title'] = $site_title . '';//云班客
	$seo['keyword'] = !empty($keyword) ? $keyword : getconfig('site_keywords');
	$seo['description'] = isset($description) && !empty($description) ? $description : (isset($cat['descript']) && !empty($cat['descript']) ? $cat['descript'] : (isset($site_description) && !empty($site_description) ? $site_description : ''));
	$seo['title'] =  (isset($title) && !empty($title) ? $title.' - ' : '').(isset($cat['title']) && !empty($cat['title']) ? $cat['title'].' - ' : (isset($cat['name']) && !empty($cat['name']) ? $cat['name'].' - ' : ''));
	foreach ($seo as $k=>$v) {
		$seo[$k] = str_replace(array("\n","\r"),	'', $v);
	}
	return $seo;
}
/**
 * 远程请求函数
 */
function _dfsockopen($url, $limit = 0, $post = '', $cookie = '', $bysocket = FALSE, $ip = '', $timeout = 15, $block = TRUE, $encodetype  = 'URLENCODE', $allowcurl = TRUE, $position = 0) {
	$return = '';
	$matches = parse_url($url);
	$scheme = $matches['scheme'];
	$host = $matches['host'];
	$path = $matches['path'] ? $matches['path'].($matches['query'] ? '?'.$matches['query'] : '') : '/';
	$port = !empty($matches['port']) ? $matches['port'] : 80;
	if(function_exists('curl_init') && function_exists('curl_exec') && $allowcurl) {
		$ch = curl_init();
		$ip && curl_setopt($ch, CURLOPT_HTTPHEADER, array("Host: ".$host));
		curl_setopt($ch, CURLOPT_URL, $scheme.'://'.($ip ? $ip : $host).':'.$port.$path);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		if($post) {
			curl_setopt($ch, CURLOPT_POST, 1);
			if($encodetype == 'URLENCODE') {
				curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
			} else {
				parse_str($post, $postarray);
				curl_setopt($ch, CURLOPT_POSTFIELDS, $postarray);
			}
		}
		if($cookie) {
			curl_setopt($ch, CURLOPT_COOKIE, $cookie);
		}
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
		curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
		$data = curl_exec($ch);
		$status = curl_getinfo($ch);
		$errno = curl_errno($ch);
		curl_close($ch);
		if($errno || $status['http_code'] != 200) {
			return;
		} else {
			return !$limit ? $data : substr($data, 0, $limit);
		}
	}
	if($post) {
		$out = "POST $path HTTP/1.0\r\n";
		$header = "Accept: */*\r\n";
		$header .= "Accept-Language: zh-cn\r\n";
		$boundary = $encodetype == 'URLENCODE' ? '' : '; boundary='.trim(substr(trim($post), 2, strpos(trim($post), "\n") - 2));
		$header .= $encodetype == 'URLENCODE' ? "Content-Type: application/x-www-form-urlencoded\r\n" : "Content-Type: multipart/form-data$boundary\r\n";
		$header .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
		$header .= "Host: $host:$port\r\n";
		$header .= 'Content-Length: '.strlen($post)."\r\n";
		$header .= "Connection: Close\r\n";
		$header .= "Cache-Control: no-cache\r\n";
		$header .= "Cookie: $cookie\r\n\r\n";
		$out .= $header.$post;
	} else {
		$out = "GET $path HTTP/1.0\r\n";
		$header = "Accept: */*\r\n";
		$header .= "Accept-Language: zh-cn\r\n";
		$header .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
		$header .= "Host: $host:$port\r\n";
		$header .= "Connection: Close\r\n";
		$header .= "Cookie: $cookie\r\n\r\n";
		$out .= $header;
	}
	$fpflag = 0;
	if(!$fp = @fsocketopen(($ip ? $ip : $host), $port, $errno, $errstr, $timeout)) {
		$context = array(
			'http' => array(
				'method' => $post ? 'POST' : 'GET',
				'header' => $header,
				'content' => $post,
				'timeout' => $timeout,
			),
		);
		$context = stream_context_create($context);
		$fp = @fopen($scheme.'://'.($ip ? $ip : $host).':'.$port.$path, 'b', false, $context);
		$fpflag = 1;
	}
	if(!$fp) {
		return '';
	} else {
		stream_set_blocking($fp, $block);
		stream_set_timeout($fp, $timeout);
		@fwrite($fp, $out);
		$status = stream_get_meta_data($fp);
		if(!$status['timed_out']) {
			while (!feof($fp) && !$fpflag) {
				if(($header = @fgets($fp)) && ($header == "\r\n" ||  $header == "\n")) {
					break;
				}
			}
			if($position) {
				for($i=0; $i<$position; $i++) {
					$char = fgetc($fp);
					if($char == "\n" && $oldchar != "\r") {
						$i++;
					}
					$oldchar = $char;
				}
			}
			if($limit) {
				$return = stream_get_contents($fp, $limit);
			} else {
				$return = stream_get_contents($fp);
			}
		}
		@fclose($fp);
		return $return;
	}
}
function remove_xss($string) { 
	 $string = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S', '', $string);
	 $parm1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
	 $parm2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
	 $parm = array_merge($parm1, $parm2); 
	for ($i = 0; $i < sizeof($parm); $i++) { 
		$pattern = '/'; 
		for ($j = 0; $j < strlen($parm[$i]); $j++) { 
			if ($j > 0) { 
				$pattern .= '('; 
				$pattern .= '(&#[x|X]0([9][a][b]);?)?'; 
				$pattern .= '|(&#0([9][10][13]);?)?'; 
				$pattern .= ')?'; 
			}
			$pattern .= $parm[$i][$j]; 
		}
		$pattern .= '/i';
		$string = preg_replace($pattern, '', $string); 
	}
	return $string;
}
function p($array) {
	 dump($array, 1, '<pre>', 0);
}
function checkinstr($str, $needle) {
	 $tmparray = explode($needle, $str);
	 if (count($tmparray) > 1) {
		  return true;
	 } else {
		  return false;
	 }
}
function is_login() {
	 return (int) authcode(cookie('user_key'), 'DECODE', C('site_key'));
}
function getUserInfo($uid = 0) {
	 $uid = ($uid > 0) ? $uid : is_login();
	 if ($uid < 1) return FALSE;
	 return M('User')->getById($uid);
}
function is_administrator($uid = null) {
	 $uid = is_null($uid) ? is_login() : $uid;
	 return $uid && (intval($uid) === C('USER_ADMINISTRATOR'));
}
function authcheck($rule, $uid, $relation = 'or') {
	 if (in_array($uid, C('ADMIN_LIST')) || in_array($rule, C('NOT_AUTH_ACTION'))) {
		  return true;	 //如果是，则直接返回真值，不需要进行权限验证
	 } else {
		  libfile('Auth');
		  $auth = new Auth();
		  return $auth->authCheck($rule, $uid, $relation) ? true : false;
	 }
}
function str2arr($str, $glue = ',') {
	 return explode($glue, $str);
}
function arr2str($arr, $glue = ',') {
	 return implode($glue, $arr);
}
function list_sort_by($list, $field, $sortby = 'asc') {
	 if (is_array($list)) {
		  $refer = $resultSet = array();
		  foreach ($list as $i => $data)
				$refer[$i] = &$data[$field];
		  switch ($sortby) {
				case 'asc': // 正向排序
					 asort($refer);
					 break;
				case 'desc':// 逆向排序
					 arsort($refer);
					 break;
				case 'nat': // 自然排序
					 natcasesort($refer);
					 break;
		  }
		  foreach ($refer as $key => $val)
				$resultSet[] = &$list[$key];
		  return $resultSet;
	 }
	 return false;
}
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
	 $ckey_length = 4;
	 $key = md5($key != '' ? $key : C('site_key'));
	 $keya = md5(substr($key, 0, 16));
	 $keyb = md5(substr($key, 16, 16));
	 $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
	 $cryptkey = $keya.md5($keya.$keyc);
	 $key_length = strlen($cryptkey);
	 $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
	 $string_length = strlen($string);
	 $result = '';
	 $box = range(0, 255);
	 $rndkey = array();
	 for($i = 0; $i <= 255; $i++) {
		  $rndkey[$i] = ord($cryptkey[$i % $key_length]);
	 }
	 for($j = $i = 0; $i < 256; $i++) {
		  $j = ($j + $box[$i] + $rndkey[$i]) % 256;
		  $tmp = $box[$i];
		  $box[$i] = $box[$j];
		  $box[$j] = $tmp;
	 }
	 for($a = $j = $i = 0; $i < $string_length; $i++) {
		  $a = ($a + 1) % 256;
		  $j = ($j + $box[$a]) % 256;
		  $tmp = $box[$a];
		  $box[$a] = $box[$j];
		  $box[$j] = $tmp;
		  $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	 }
	 if($operation == 'DECODE') {
		  if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
				return substr($result, 26);
		  } else {
				return '';
		  }
	 } else {
		  return $keyc.str_replace('=', '', base64_encode($result));
	 }
}
function data_auth_sign($data) {
	 //数据类型检测
	 if (!is_array($data)) {
		  $data = (array) $data;
	 }
	 ksort($data); //排序
	 $code = http_build_query($data); //url编码并生成query字符串
	 $sign = sha1($code); //生成签名
	 return $sign;
}
function list_to_tree($list, $pk = 'id', $pid = 'parentid', $child = '_child', $root = 0) {
	 // 创建Tree
	 $tree = array();
	 if (is_array($list)) {
		  // 创建基于主键的数组引用
		  $refer = array();
		  foreach ($list as $key => $data) {
				$refer[$data[$pk]] = & $list[$key];
		  }
		  foreach ($list as $key => $data) {
				// 判断是否存在parent
				$parentId = $data[$pid];
				if ($root == $parentId) {
					 $tree[$data[$pk]] = & $list[$key];
				} else {
					 if (isset($refer[$parentId])) {
						  $parent = & $refer[$parentId];
						  $parent[$child][$data[$pk]] = & $list[$key];
					 }
				}
		  }
	 }
	 return $tree;
}
function tree_to_list($tree, $child = '_child', $order = 'id', &$list = array()) {
	 if (is_array($tree)) {
		  $refer = array();
		  foreach ($tree as $key => $value) {
				$reffer = $value;
				if (isset($reffer[$child])) {
					 unset($reffer[$child]);
					 tree_to_list($value[$child], $child, $order, $list);
				}
				$list[] = $reffer;
		  }
		  $list = list_sort_by($list, $order, $sortby = 'asc');
	 }
	 return $list;
}
function format_bytes($size, $delimiter = '') {
	 $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
	 for ($i = 0; $size >= 1024 && $i < 5; $i++)
		  $size /= 1024;
	 return round($size, 2) . $delimiter . $units[$i];
}
function set_redirect_url($url) {
	 cookie('redirect_url', $url);
}
function get_redirect_url() {
	 $url = cookie('redirect_url');
	 return empty($url) ? __APP__ : $url;
}
function get_nickname($uid = 0) {
	$name = M('User')->getFieldById($uid, 'username');
	 return $name;
}
function get_category($id, $field = null) {
	 static $list;
	 /* 非法分类ID */
	 if (empty($id) || !is_numeric($id)) {
		  return '';
	 }
	 /* 读取缓存数据 */
	 if (empty($list)) {
		  $list = S('sys_category_list');
	 }
	 /* 获取分类名称 */
	 if (!isset($list[$id])) {
		  $cate = M('Category')->find($id);
		  if (!$cate || 1 != $cate['status']) { //不存在分类，或分类被禁用
				return '';
		  }
		  $list[$id] = $cate;
		  S('sys_category_list', $list); //更新缓存
	 }
	 return is_null($field) ? $list[$id] : $list[$id][$field];
}
function getTree($list,$parent_id,$level=0){
	 static $tree=array();
	 foreach ($list as $row){
		  if($row['parent_id']==$parent_id){
				$row['level']=$level;
				$tree[]=$row;
				getTree($list, $row['id'],$level+1);
		  }
	 }
	 return $tree;
}
/* 根据ID获取分类标识 */
function get_category_name($id) {
	 return get_category($id, 'name');
}
/* 根据ID获取分类名称 */
function get_category_title($id) {
	 return get_category($id, 'title');
}
function action_log($msg = '') {
	 return model('admin_action_log')->write_log($msg);
}
//基于数组创建目录和文件
function create_dir_or_files($files) {
	 foreach ($files as $key => $value) {
		  if (substr($value, -1) == '/') {
				mkdir($value);
		  } else {
				@file_put_contents($value, '');
		  }
	 }
}
if (!function_exists('array_column')) {
	 function array_column(array $input, $columnKey, $indexKey = null) {
		  $result = array();
		  if (null === $indexKey) {
				if (null === $columnKey) {
					 $result = array_values($input);
				} else {
					 foreach ($input as $row) {
						  $result[] = $row[$columnKey];
					 }
				}
		  } else {
				if (null === $columnKey) {
					 foreach ($input as $row) {
						  $result[$row[$indexKey]] = $row;
					 }
				} else {
					 foreach ($input as $row) {
						  $result[$row[$indexKey]] = $row[$columnKey];
					 }
				}
		  }
		  return $result;
	 }
}
function get_table_name($model_id = null) {
	 if (empty($model_id)) {
		  return false;
	 }
	 $Model = M('Model');
	 $name = '';
	 $info = $Model->getById($model_id);
	 if ($info['extend'] != 0) {
		  $name = $Model->getFieldById($info['extend'], 'name') . '_';
	 }
	 $name .= $info['name'];
	 return $name;
}
function get_model_attribute($model_id, $group = true) {
	 static $list;
	 /* 非法ID */
	 if (empty($model_id) || !is_numeric($model_id)) {
		  return '';
	 }
	 /* 读取缓存数据 */
	 if (empty($list)) {
		  $list = S('attribute_list');
	 }
	 /* 获取属性 */
	 if (!isset($list[$model_id])) {
		  $map = array('model_id' => $model_id);
		  $extend = M('Model')->getFieldById($model_id, 'extend');
		  if ($extend) {
				$map = array('model_id' => array("in", array($model_id, $extend)));
		  }
		  $info = M('Attribute')->where($map)->select();
		  $list[$model_id] = $info;
		  //S('attribute_list', $list); //更新缓存
	 }
	 $attr = array();
	 foreach ($list[$model_id] as $value) {
		  $attr[$value['id']] = $value;
	 }
	 if ($group) {
		  $sort = M('Model')->getFieldById($model_id, 'field_sort');
		  if (empty($sort)) { //未排序
				$group = array(1 => array_merge($attr));
		  } else {
				$group = json_decode($sort, true);
				$keys = array_keys($group);
				foreach ($group as &$value) {
					 foreach ($value as $key => $val) {
						  $value[$key] = $attr[$val];
						  unset($attr[$val]);
					 }
				}
				if (!empty($attr)) {
					 $group[$keys[0]] = array_merge($group[$keys[0]], $attr);
				}
		  }
		  $attr = $group;
	 }
	 return $attr;
}
function api($name, $vars = array()) {
	 $array = explode('/', $name);
	 $method = array_pop($array);
	 $classname = array_pop($array);
	 $module = $array ? array_pop($array) : 'Common';
	 $callback = $module . '\\Api\\' . $classname . 'Api::' . $method;
	 if (is_string($vars)) {
		  parse_str($vars, $vars);
	 }
	 return call_user_func_array($callback, $vars);
}
function arrayChange($a){
	 static $arr2;
	 foreach($a as $v){
		  if(is_array($v)){
				arrayChange($v);
		  }else{
				$arr2[]=$v;
		  }
	 }
	 return $arr2;
}
function get_table_field($value = null, $condition = 'id', $field = null, $table = null) {
	 if (empty($value) || empty($table)) {
		  return false;
	 }
	 //拼接参数
	 $map[$condition] = $value;
	 $info = M(ucfirst($table))->where($map);
	 if (empty($field)) {
		  $info = $info->field(true)->find();
	 } else {
		  $info = $info->getField($field);
	 }
	 return $info;
}
function status_text($status) {
	 if ($status == 1)
		  $txt = '正常';
	 if ($status == 0)
		  $txt = '禁用';
	 return $txt;
}
function space($num,$str='&nbsp;&nbsp;'){
	 for($i=0;$i<$num;$i++){
		  $_temp.=$str;
	 }
	 return $_temp;
}
function checkstatus($obj,$field,$list,$val='none'){
		  if(!empty($list)){
				$sta = M($obj);
				if($val=='none'){
						  $data[$field]=array('exp',' 1-status ');
				}else{
						  $data[$field] = intval($val);
				}
				if(is_array($list)){
					 foreach($list as $value){
						  $sta->where(array('id'=>$value))->save($data);
					 }				  
				}else{
					$sta->where(array('id'=>$list))->save($data); 
				}
				return true;
		  }else{
				return false;
		  }
}
function checkdelete($obj,$list){
		  if(!empty($list)){
					 $sc = M($obj);
					 $sc->where(array('id'=>array('in',$list)))->delete();
					 return true;
		  }else{
					 return false;
		  }
}
function  SendMail($address,$title,$message) {
	 libfile('Smtp');
	 $map=array();
	 $map['code']='email';
	 $config_json=model('notify')->where($map)->getField('config');
     $config=json_decode($config_json,true);
     $smtpserver = $config['mail_smtpserver'];
	 $port		 = $config['mail_smtpport'];
	 $smtpuser	= $config['mail_mailuser'];
	 $smtppwd	 = $config['mail_mailpass'];
	 $from      = $config['mail_formmail'];
	 $mailtype	= "HTML";
	 $smtp = new Smtp($smtpserver, $port, true, $smtpuser, $smtppwd, $address);
	 $send = $smtp->sendmail($address, $from, $title, $message, $mailtype);
	 // 发送邮件。
	 return $send;
}
function build_order_no() {
	 return date('YmdHis').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 6);
}
function generate_password( $length = 8 ) {
	 $chars = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789';
	 $password = '';
	 for ($i = 0; $i < $length; $i++){
		  $password .= $chars[mt_rand(0, strlen($chars) - 1)];
	 }
	 return $password;
}
function clearCache(){
}
function msubstr($str, $length, $start=0, $charset="utf-8", $suffix=true){
	 if(function_exists("mb_substr")){
		  if($suffix){
			  	if(strlen($str)<$length)return mb_substr($str, $start, $length, $charset);
				else return mb_substr($str, $start, $length, $charset);
		  }else{
				return mb_substr($str, $start, $length, $charset);
		  }
	 }elseif(function_exists('iconv_substr')) {
		  if($suffix){
				if(strlen($str)<$length)return iconv_substr($str,$start,$length,$charset);
				else return iconv_substr($str,$start,$length,$charset);
		  }else{
				return iconv_substr($str,$start,$length,$charset);
		  }
	 }
	 $re['utf-8']	= "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
	 $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
	 $re['gbk']	 = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
	 $re['big5']	= "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
	 preg_match_all($re[$charset], $str, $match);
	 $slice = join("",array_slice($match[0], $start, $length));
	 if($suffix){
		 return $slice;
	 } else {
		  return $slice;
	 }
}
/**
* 转化 \ 为 /
* 
* @param	 string  $path	路径
* @return	string  路径
*/
function dir_path($path) {
	 $path = str_replace('\\', '/', $path);
	 if(substr($path, -1) != '/') $path = $path.'/';
	 return $path;
}
function dir_create($path, $mode = 0777) {
	 if(is_dir($path)) return TRUE;
	 $ftp_enable = 0;
	 $path = dir_path($path);
	 $temp = explode('/', $path);
	 $cur_dir = '';
	 $max = count($temp) - 1;
	 for($i=0; $i<$max; $i++) {
		  $cur_dir .= $temp[$i].'/';
		  if (@is_dir($cur_dir)) continue;
		  @mkdir($cur_dir, 0777,true);
		  @chmod($cur_dir, 0777);
	 }
	 return is_dir($path);
}
/**
 * 编译模板缓存文件
 * @param  string $maintpl	  模板路径
 * @param  [type] $cachefile	缓存路径
 * @param  [type] $timecompare 缓存时间
 * @return [type]				  [description]
 */
function checktplrefresh($maintpl, $cachefile, $timecompare = 1) {
	static $tplrefresh, $timestamp;
	$tplrefresh = C('TMPL_CACHE_ON');
	$timestamp = NOW_TIME;
	if(empty($timecompare) || $tplrefresh === FALSE || !file_exists($cachefile) ||  @filemtime($cachefile) - $timestamp > $timecompare) {
		libfile('Template');
		$template = new Template();
		$template->parse_template($maintpl, $cachefile);
		return TRUE;
	}
	return FALSE;
}
/* 获取模板路径 */
function template($file = '', $module = '') {
    $oldfile = $file;
    $suffix = C('TMPL_TEMPLATE_SUFFIX');
    $module = strtolower((empty($module)) ? GROUP_NAME : $module);
    $theme_path = (defined('IS_MOBILE')) ? 'wap' : C('TMPL_THEME');
    if(strpos($file, ':') !== false) {
        list($theme, $file) = explode(':', $file);
        if ($theme != C('TMPL_THEME') && defined('IN_PLUGIN')) {
            $tpldir = 'plugin/'.PLUGIN_ID.'/template';
        } else {
            $tpldir = TMPL_PATH.$theme_path.'/'.$module;            
        }
    } elseif(strpos($file, '/') !== false) {
    	$tpldir = TMPL_PATH.$theme_path;
    }else {
        $tpldir = TMPL_PATH.$theme_path.'/'.$module;
    }
    $file .= IS_AJAX ? '_ajax' : '';//如果是ajax模板
    $filebak = $file;
    $tplfile = $tpldir.strtolower('/'.$file.$suffix);
    $md5file = strtolower(md5($tpldir.'/'.$file).$suffix);
    $cachefile = CACHE_PATH.substr($md5file, 0, -strlen($suffix)).'.php';
    if(!file_exists($tplfile) && !file_exists(substr($tplfile, 0, -4).'.php')) {
        $tplfile = TMPL_PATH.'default/'.strtolower($module.'/'.$filebak.C('TMPL_TEMPLATE_SUFFIX'));
    }
    /* 检查模板缓存 */
    checktplrefresh($tplfile, $cachefile, @filemtime($cachefile));
    return $cachefile;
}
/**
 * 检测字符串包含
 */
function strexists($string, $find) {
	 return !(strpos($string, $find) === FALSE);
}
/**
 * 提示信息页面跳转，跳转地址如果传入数组，页面会提示多个地址供用户选择，默认跳转地址为数组的第一个值，时间为5秒。
 * showmessage('登录成功', array('默认跳转地址'=>'http://www.phpcms.cn'));
 * @param string $msg 提示信息
 * @param mixed(string/array) $url_forward 跳转地址
 * @param int $ms 跳转等待时间
 */
function showmessage($msg, $url_forward = 'goback', $status = 0, $ms = 1500, $dialog = '', $returnjs = '', $extra = array()) {
	 $suffix = ($status == 1) ? '_success' : '_error';
	 runhook(strtolower(GROUP_NAME.'_'.MODULE_NAME.'_'.ACTION_NAME.$suffix));
	 if (IS_AJAX) {
		  $result = array();
		  $result['status'] = $status;
		  $result['info'] = $msg;
		  $result['url'] = $url_forward;
		  $result['ms'] = $ms;
		  if($extra) {
				$result = array_merge($result, $extra);
		  }
		  echo json_encode($result);
		  exit();
	 }
	 if(defined('IN_ADMIN')) {
	 	include A('Base')->admin_tpl('showmessage');
	 } else {
	 	include (template('showmessage', 'common'));
	 }
	 exit;
}
/**
 * 时间格式化
 * @param  int $timestamp 时间戳
 * @param  string  $format	 格式
 * @return string
 */
function mdate($timestamp=0, $format='Y-m-d H:i:s') {
	 $times = intval($timestamp);
	 if(!$times) return false;
	 return date($format,$times);
}
function pages($count, $num, $page){
	 libfile('Page');
	 $Page = new Page($count, $num);
	 $pages = $Page->show();
	 return $pages;
}
/**
 * 获取系统信息
 */
function get_sysinfo() {
	 $sys_info['os']				 = PHP_OS;//当前操作系统的类型
	 $sys_info['zlib']			  = function_exists('gzclose');//zlib
	 $sys_info['safe_mode']		= (boolean) ini_get('safe_mode');//safe_mode = Off 
	 $sys_info['safe_mode_gid']  = (boolean) ini_get('safe_mode_gid');//safe_mode_gid = Off
	 $sys_info['timezone']		 = function_exists("date_default_timezone_get") ? date_default_timezone_get() : L('no_setting');
	 $sys_info['socket']			= function_exists('fsockopen') ;
	 $sys_info['web_server']	  = strpos($_SERVER['SERVER_SOFTWARE'], 'PHP')===false ? $_SERVER['SERVER_SOFTWARE'].'PHP/'.phpversion() : $_SERVER['SERVER_SOFTWARE'];
	 $sys_info['phpv']			  = phpversion(); 
	 $sys_info['mysqlv'] = mysql_get_server_info();
	 $sys_info['fileupload']	  = @ini_get('file_uploads') ? ini_get('upload_max_filesize') :'unknown';
	 $sys_info['mysqlsize']		= M()->query("select round(sum(DATA_LENGTH/1024/1024)+sum(DATA_LENGTH/1024/1024),2) as db_length from information_schema.tables 
where table_schema='".C('DB_NAME')."'");
	 $sys_info['mysqlsize']		= $sys_info['mysqlsize'][0]['db_length'];
	 return $sys_info;
}
/**
 * 当前路径
 * 返回指定栏目路径层级
 * @param $catid 栏目id
 * @param $symbol 栏目间隔符
 */
function catpos($catid, $symbol=' > ') {
	 $categorys = getcache('goods_category', 'goods');
	 $pos = '';
	 $parentids = D('Admin/Category')->getParent($catid, 0);	 
	 if (empty($parentids)) return FALSE;
	 asort($parentids);
	 foreach ($parentids as $parentid) {
		  $url = U('Goods/Index/lists', array('id' => $parentid));
		  $pos .= '<a href="'.$url.'">'.$categorys[$parentid]['name'].'</a>'.$symbol;
	 }
	 return $pos;
}
function catposArticle($catid, $symbol=' > ') {
	 $categorys = D('ArticleCategory')->select();
	 $pos = '';
	 $parentids = D('ArticleCategory')->field('name')->where(array('id'=>$catid))->select();  
	 if (empty($parentids)) return FALSE;
	 asort($parentids);
	 foreach ($parentids as $parentid) {
		  $url = U('Article/Index/lists', array('id' => $catid));
		  $pos .= $symbol.'<a href="'.$url.'">'.$parentid['name'].'</a>';
	 }
	 return $pos;
}
/**
 * 电子邮箱格式判断
 * @param  string $email 字符串
 * @return bool
 */
function is_email($email) {
	 if (!empty($email)) {
		  return preg_match('/^[a-z0-9]+([\+_\-\.]?[a-z0-9]+)*@([a-z0-9]+[\-]?[a-z0-9]+\.)+[a-z]{2,6}$/i', $email);
	 }
	 return FALSE;
}
function is_mobile($string){
	 if (!empty($string)) {
		  return preg_match('/^1[3|4|5|7|8][0-9]\d{8}$/', $string);
	 }
	 return FALSE;
}
function group_name($group_id){
	return model('user_group')->getFieldById($group_id, 'name');
}
function utype_name($type){
	return $type==1?"个人会员":"商家会员";
}
function getconfig($name=null, $value=null) {
	return C($name, $value);
}
/**
 * 获取地区名称
 * @param int $id 地区ID
 */
function getAreaNameById($id) {
	return M('Region')->where(array('area_id' => $id))->getField('area_name');
}
/**
 * 获取订单商品
 * @param int $order_id 订单ID
 */
function getGoodsInfoByOrderId($order_id, $limit = 3){
	$sqlmap = $result = array();
	$sqlmap['order_id'] = $order_id;
	$result['nums'] = model('order_goods')->where($sqlmap)->count();
	$result['info'] = model('order_goods')->where($sqlmap)->limit($limit)->select();
	return $result;
}
function create_url($k, $v, $attr) {	
	$url = parse_url(__SELF__);
	parse_str($url['query'], $param);
	$param = dstripslashes($param);
	if(in_array($k, $attr)) {
		$param['attr'][$k] = $v;
	} else {
		$param[$k] = $v;
	}
	 $param['page'] = 0;
	$param = array_filter($param);
	$param['attr'] = array_filter($param['attr']);
	return urldecode($url['path'].'?'.http_build_query($param));
}
/**
 * 变更用户积分
 */
function action_point($uid, $point, $descript, $isrun = TRUE) {
	$uid = (int) $uid;
	$point = (int) $point;
	$log = array();
	$log['user_id'] = $uid;
	$log['pay_points'] = $point;
	$log['descript'] = $descript;
	$log['time'] = NOW_TIME;
	$result = D('UserPointslog')->add($log);
	if($result && $isrun === TRUE) {
		if($point > 0) {
			M('User')->where(array('id' => $uid))->setInc('pay_points', $point);
		} else {
			M('User')->where(array('id' => $uid))->setDec('pay_points', $point);
		}
		return TRUE;
	}
	return FALSE;
}
/**
 * 经验变更
 */
function action_exp($uid, $exp) {
	$uid = (int) $uid;
	$exp = (int) $exp;
	$oldxp = M('User')->getFieldById($uid, 'exp');
	$info['id'] = $uid;
	$info['exp'] = $oldxp + $exp;
	$sqlmap['min_points'] = array("ELT", $info['exp']);
	$sqlmap['max_points'] = array("GT", $info['exp']);
	$group_id = M('UserGroup')->where($sqlmap)->getField('id');
	if($group_id < 1) return FALSE;
	$info['group_id'] = $group_id;
	M('User')->save($info);
	return TRUE;	
}
/**
 * 优惠券变更
 */
function action_coupons($uid, $cid, $num = 1){
	$uid = (int) $uid;
	$cid = (int) $cid;
	$num = (int) $num;
	$cmap['cid'] = array("EQ", $cid);
	$cmap['status'] = array("EQ", 0);
	$crs = model('coupons_list')->where($cmap)->limit($num)->select();
	foreach ($crs as $key => $value) {
		$umap['id'] = $value['id'];
		$data['user_id'] = $uid;
		$data['status'] = '1';
		model('coupons_list')->where($umap)->save($data);
	}
	return TRUE;
}
/* 实例化数据表 */
function model($name, $layer = '', $baseurl) {
	$tablename = parse_name($name, 1);
	if(defined('IN_PLUGIN')) {
		$baseurl = PLUGIN_PATH.PLUGIN_ID.'/model';
	}
	return D($tablename, $layer, $baseurl);
}
/**
 * 执行SQL语句
 * @param  string $sqlquery SQL语句，支持多条
 * @return bool
 */
function sqlexecute($sqlquery = '') {
	 if(empty($sqlquery)) return FALSE;
	 $sqlquery = str_replace('{prefix}', C('DB_PREFIX'), $sqlquery);
	 $version = M()->query("select version() as v;");
	 $version = intval($version[0]['v']);
	 if($version > '4.1' && C('DEFAULT_CHARSET')) {
		  $sqlquery = preg_replace("/TYPE=(InnoDB|MyISAM|MEMORY)( DEFAULT CHARSET=[^; ]+)?/", "ENGINE=\\1 DEFAULT CHARSET=utf8;", $sqlquery);
	 }				
	 $sqlquery = str_replace("\r", "\n", $sqlquery);
	 $queriesarray = explode(";\n", trim($sqlquery));
	 foreach ($queriesarray as $query) {
		  if (substr($query, 0, 1) != '#' && substr($query, 0, 1) != '-') {
				M()->execute($query);
		  }
	 }
	 return TRUE;
}
function multi_array_sort(&$multi_array,$sort_key,$sort=SORT_DESC){
	 if(is_array($multi_array)){
		  foreach ($multi_array as $row_array){
				if(is_array($row_array)){
					 $key_array[] = $row_array[$sort_key];
				}else{
					 return false;
				}
		  }
	 } else {
		  return false;
	 }
	 array_multisort($key_array,$sort,$multi_array);
	 return $multi_array;
}
//[代金券]获取代金券数量
function getCouponsCount($id,$status){
	$where['cid'] = $id;
	if(isset($status)){
		$where['status']=$status;
	}
		return M('coupons_list')->where($where)->count();
	}
//获取会员表信息
function getMemberfield($id,$field){
	$where['id']=$id;
	$field=$field;
	return M('user')->where($where)->getField($field);
}
function getGoodsNumber($goods_id,$products_id,$field){
	$r = D('Goods')->detail($goods_id,$products_id);
		if($products_id && $field == 'name'){
			$spec_arr = unserialize($r['spec_array']);
			foreach ($spec_arr as $k => $v) {
				$spec_arr_text .= '['.$v['name'].':'.$v['value'].'] ';
			}
			$r['name'] = $r['name'].' '.$spec_arr_text;
		}
		return $r[$field];
}
function format_price($min,$max=0){
	$r = $min . '-' . $max;
	if($max == 0) $r = $min;
	if($min == $max) $_r = $min;
	return $r;
}
function array2string($data, $isformdata = 1) {
    if($data == '') return '';
    if($isformdata) $data = dstripslashes($data);
    return var_export($data, TRUE);
}
function string2array($data) {
    if($data == '') return array();
    @eval("\$array = $data;");
    return $array;
}
function array_merge_multi ()
{
    $args = func_get_args();
    $array = array();
    foreach ( $args as $arg ) {
        if ( is_array($arg) ) {
            foreach ( $arg as $k => $v ) {
                if ( is_array($v) ) {
                    $array[$k] = isset($array[$k]) ? $array[$k] : array();
                    $array[$k] = array_merge_multi($array[$k], $v);
                } else {
                    $array[$k] = $v;
                }
            }
        }
    }
    return $array;
}
function get_user_name($uid){
	$user=M("user")->where("id=".$uid)->find();
	return $user["username"];
}
function get_user_mobile($uid){
	$user=M("user")->where("id=".$uid)->find();
	return $user["mobile_phone"];
}
function get_user_compay($uid){
	$user=M("user")->where("id=".$uid)->find();
	return $user["compayname"]==""?"暂无":$user["compayname"];
}
function sendsms($mob, $content){

	
	// $json['status'] = 1;
	// $json['info'] = $content;
	// exit(json_encode($json));


	$referer = $_SERVER['HTTP_REFERER'];    
    if($referer) {$refererArr = parse_url($referer);$host=$refererArr['host'];}
    if(empty($host)){return '非法操作';}
    if(!empty($_SERVER['HTTP_VIA']))    //使用了代理
	{
	    if(!isset($_SERVER['HTTP_X_FORWARDED_FOR']))
	    {
	        //Anonymous Proxies    普通匿名代理服务器
	    	return '您的操作过于频繁，请稍后重试。';
	       // echo "代理IP地址为". $_SERVER['REMOTE_ADDR'];
	   }
	   else
	   {
	   		//return '您的操作过于频繁，请稍后重试。';
	        //Transparent Proxies 透明代理服务器
	         //echo "代理IP地址为". $_SERVER['REMOTE_ADDR'];
	         //echo "真实ip地址为". $_SERVER['HTTP_X_FORWARDED_FOR'];
	   }
	}
    $client_ip = explode(':', get_client_ip(),2);
    $addData['content'] = $content;
    $addData['type'] = 0;
    $addData['cellphone'] = $mob;
    $addData['add_time'] = time();
    $addData['add_ip'] = $client_ip[0];    
    $addData['status'] = 0;
	$m = M('log_sms');
	 //限制一：12小时内不得超过300
    $countCellphone12ha = $m->where("FROM_UNIXTIME(`add_time`) >= DATE_SUB(NOW(),INTERVAL 12 HOUR) and status>0")->count('id');
    if($countCellphone12ha>1000) {return '您的操作过于频繁，请稍后重试。';}
    $countCellphone1ha = $m->where("FROM_UNIXTIME(`add_time`) >= DATE_SUB(NOW(),INTERVAL 1 HOUR) and status>0")->count('id');
    if($countCellphone1ha>200) {return '您的操作过于频繁，请稍后重试。';}
    //限制二：单个手机号12小时不得超过20;
    $countCellphone12hs = $m->where("`cellphone` = '{$mob}' and FROM_UNIXTIME(`add_time`) >= DATE_SUB(NOW(),INTERVAL 12 HOUR) and status>0")->count('id');
    if($countCellphone12hs>20) {return '您的操作过于频繁，请稍后重试。';}
    //限制三：单个手机号300秒不得超过3条
    $countCellphone = $m->where("`cellphone` = '{$mob}' and add_time > (unix_timestamp()-300)")->count('id');
    if($countCellphone>3) {return '您的操作过于频繁，请稍后重试。';}
  	$handle = file_get_contents("del_sms_log.txt", "r");
	if($handle!=date("Y-m-d")){ 
		$fp=fopen("del_sms_log.txt","w");   
		fwrite($fp, date("Y-m-d"));
		fclose($fp);
		$m->where("add_time<".strtotime('-7days'))->delete();    
	}
    $newid = $m->add($addData);
	$uid = C("SMS_USER.uid");
    $pwd = C("SMS_USER.pwd");
    $mob = $mob;
    $content = urlencode(auto_charset($content, "utf-8", "gbk"));
    $sendurl = "http://service.winic.org:8009/sys_port/gateway/?id=" . $uid . "&pwd=" . $pwd . "&to=" . $mob . "&content=" . $content . "&time=";
	$s=@file_get_contents($sendurl);
    $data = explode("/", $s);
    if ($data[0] == "000") {
		$m->save(array('status'=>1,'id'=>$newid));
        return true;
    } else {
		$m->save(array('status'=>2,'id'=>$newid));
        return false;
    }	
}




function auto_charset($fContents, $from = "gbk", $to = "utf-8")
{
    $from = strtoupper($from) == "UTF8" ? "utf-8" : $from;
    $to = strtoupper($to) == "UTF8" ? "utf-8" : $to;
    if ($to == "utf-8" && is_utf8($fContents) || strtoupper($from) === strtoupper($to) || empty($fContents) || is_scalar($fContents) && !is_string($fContents)) {
        return $fContents;
    }
    if (is_string($fContents)) {
        if (function_exists("mb_convert_encoding")) {
            return mb_convert_encoding($fContents, $to, $from);
        } else if (function_exists("iconv")) {
            return iconv($from, $to, $fContents);
        } else {
            return $fContents;
        }
    } else if (is_array($fContents)) {
        foreach ($fContents as $key => $val) {
            $_key = auto_charset($key, $from, $to);
            $fContents[$_key] = auto_charset($val, $from, $to);
            if ($key != $_key) {
                unset($fContents[$key]);
            }
        }
        return $fContents;
    } else {
        return $fContents;
    }
}
function is_utf8($string)
{
    return preg_match("%^(?:\r\n\t\t [\\x09\\x0A\\x0D\\x20-\\x7E]            # ASCII\r\n\t   | [\\xC2-\\xDF][\\x80-\\xBF]             # non-overlong 2-byte\r\n\t   |  \\xE0[\\xA0-\\xBF][\\x80-\\xBF]        # excluding overlongs\r\n\t   | [\\xE1-\\xEC\\xEE\\xEF][\\x80-\\xBF]{2}  # straight 3-byte\r\n\t   |  \\xED[\\x80-\\x9F][\\x80-\\xBF]        # excluding surrogates\r\n\t   |  \\xF0[\\x90-\\xBF][\\x80-\\xBF]{2}     # planes 1-3\r\n\t   | [\\xF1-\\xF3][\\x80-\\xBF]{3}          # planes 4-15\r\n\t   |  \\xF4[\\x80-\\x8F][\\x80-\\xBF]{2}     # plane 16\r\n   )*\$%xs", $string);
}
function check_money($uid){
	//M("user")->startTrans();
	$order=model('order');
	$user_rebate=M("user_rebate");
	$all_money=$order->where(array('user_id' => $uid, 'order_status' => 2))->sum("real_amount");
	$user_rebate=M("user")->field("rebate_num,old_rebate_num")->where("id=".$uid)->find();
	$all_rebate=$user_rebate["rebate_num"]+$user_rebate["old_rebate_num"];
	if($all_money>0){
		$all_num=bcsub(floor($all_money/1000),$all_rebate);
		if($all_num>0){
			$rebate_log['user_id'] = $uid;
			$rebate_log['save_num'] = $all_num;
			$rebate_log['msg'] = "赠送金额满足条件新增".$all_num."个赠送权";
			$rebate_log['add_time'] = NOW_TIME;
			$rebate_log['type'] = 1;
			$rebate_log['rebate_num'] = $user_rebate['rebate_num']+$all_num;
			$rebate_log['old_rebate_num'] = $user_rebate['old_rebate_num'];
			$rebate_log_arr[]=$rebate_log;
			$is_send=M('user_rebate_log')->addAll($rebate_log_arr);
			$is_add=M("user")->where('id='.$uid)->setInc('rebate_num',$all_num); 
			if ($is_send!==false and $is_add!==false){ 
				//M("user")->commit();
			}else{
				//M("user")->rollback();
			}
		}		
	}
}
function check_money_sell($uid){
	$order=model('order');
	$user_rebate=M("user_rebate");
	$all_money=$order->where(array('sell_uid' => $uid, 'order_status' => 2))->sum("real_amount");
	$user_rebate=M("user")->field("rebate_sell_num,old_rebate_sell_num")->where("id=".$uid)->find();
	$all_rebate=$user_rebate["rebate_sell_num"]+$user_rebate["old_rebate_sell_num"];
	if($all_money>0){
		$all_num=bcsub(floor($all_money/5000*0.12),$all_rebate);
		if($all_num>0){
			$rebate_log['user_id'] = $uid;
			$rebate_log['save_num'] = $all_num;
			$rebate_log['msg'] = "赠送金额满足条件新增".$all_num."个赠送权";
			$rebate_log['add_time'] = NOW_TIME;
			$rebate_log['type'] = 1;
			$rebate_log['rebate_num'] = $user_rebate['rebate_sell_num']+$all_num;
			$rebate_log['old_rebate_num'] = $user_rebate['old_rebate_sell_num'];
			$rebate_log_arr[]=$rebate_log;
			$is_send=M('user_sell_rebate_log')->addAll($rebate_log_arr);
			$is_add=M("user")->where('id='.$uid)->setInc('rebate_sell_num',$all_num); 
			if ($is_send!==false and $is_add!==false){ 
				//M("user")->commit();
			}else{
				//M("user")->rollback();
			}
		}		
	}
}
function jason_fanli(){
	echo "系统执行过程中清不要关闭页面！！！";
	$user_rebate_set=M("user_rebate_set")->find();
	$star_times=strtotime(date('Y-m-d',time())." ".$user_rebate_set["open_time1"].":".$user_rebate_set["open_time2"]);
	if($star_times<time() and $user_rebate_set["status"]==1){
		G('begin');
		$is_fafang_time=strtotime(date('Y-m-d 00:00:01',time()));
		if($user_rebate_set["lasttime"]>$is_fafang_time){
			echo '红利发放完毕';  
			exit;   
		}
		$next_num=$user_rebate_set["next_num"];
		$Rebate=M("user_rebate");
		$Rebatelog=M("user_rebate_log");
		$User=M("user");
		if($user_rebate_set["return_type"]==1){
			$money=$user_rebate_set["return_money"];
		}else{
			$map_today['sell_uid'] = array("neq",0);
			$amount_all=$amount_all==0?"0.00":$amount_all;
			$start=strtotime(date("Y/m/d", strtotime('-1 day'))." 00:00:01");
			$end=strtotime(date("Y/m/d", strtotime('-1 day'))." 23:59:59"); 
			$map_today['create_time'] =array('between',$start.','.$end);
			$map_today['sell_uid'] = array("neq",0);
			$amount_yesterday = model('order')->where($map_today)->sum('real_amount');
			$amount_yesterday=$amount_yesterday==0?"0.00":$amount_yesterday;
			$all_num=M("user")->sum("rebate_num");
			$money=$amount_yesterday*0.1*$user_rebate_set["return_per"]/100/$all_num;
		}
		$return_type=$user_rebate_set["return_type"];
		if($money<0.01){
			echo '红利发放失败,错误代码098';  
			exit;   
		}
		$user_num=0;
		$all_num=0;//人数
		$Rebate->startTrans();
		$all_list=M("user u")->field("id,rebate_num,old_rebate_num,user_money,freeze_money,pay_points as return_money")->select();
		foreach($all_list as $key=>$val){
			if($val["rebate_num"]>0){
				//更新账户信息
				$return_money=$val["rebate_num"]*$money;
				$where['id']=$val["id"];
				$where['user_money']=array('exp','user_money+'.$return_money);
				$where['pay_points']=array('exp','pay_points+'.$return_money);
				$all_return=$val["return_money"]+$return_money;
				$all_num_over=floor($all_return/1000);
				if($all_num_over>$val["old_rebate_num"]){
					$last_num=bcsub($all_num_over,$val["old_rebate_num"],0);
					$where['old_rebate_num']=array('exp','old_rebate_num+'.$last_num);
					$where['rebate_num']=array('exp','rebate_num-'.$last_num);
					$rebate_log['user_id'] = $val["id"];
					$rebate_log['save_num'] = $last_num;
					$rebate_log['msg'] = "赠送金额满足条件取消".$last_num."个赠送权";
					$rebate_log['add_time'] = NOW_TIME;
					$rebate_log['type'] = 2;
					$rebate_log['rebate_num'] = bcsub($val["rebate_num"],$last_num,0);
					$rebate_log['old_rebate_num'] = $val["old_rebate_num"]+$last_num;
					$rebate_log_arr[]=$rebate_log;
					unset($rebate_log);
				}
				$save_money_arr[]=serialize($where);
				unset($where);
				//插入资金变动记录
				$user_money['user_id'] = $val["id"];
				$user_money['money'] = $return_money;
				$user_money['msg'] = "赠送发放";
				$user_money['info']="赠送发放：".$return_money."元 X ".$val["rebate_num"]."个赠送权";
				$user_money['dateline'] = NOW_TIME;
				$user_money['type'] = 9;
				$user_money['user_money'] = $val["user_money"]+$return_money;
				$user_money['freeze_money'] = $val["freeze_money"];
				$user_money['pay_points'] =$val["return_money"]+$return_money;
				$user_moneylog[]=$user_money;
				$all_money+=$return_money;// 总金额
				$all_num+=$val["rebate_num"]; //总赠送权数量
				$all_user+=1;//总用户数
				unset($user_money);
				unset($return_money);
				unset($last_num);
			}
		}
		if(count($save_money_arr)>0){
			foreach($save_money_arr as $valc){
				$valc=unserialize($valc);
				$update_points=$User->save($valc);
				if($update_points === false ){$update_points=false;continue;}
			}
		}else{
			$update_points=true;    
		}
		if(count($user_moneylog)>0){
			$is_save_user_moneylog=m('User_moneylog')->addAll($user_moneylog);//更新资金记录
		}else{
			$is_user_rebate_log=true;
		}
		if(count($rebate_log_arr)>0){
			$is_user_rebate_log=M('user_rebate_log')->addAll($rebate_log_arr);//更新赠送权记录
		}else{
			$is_user_rebate_log=true;
		}
		// echo "<pre>";
		// print_r($user_moneylog);
		// echo M('user_rebate_log')->getlastsql();
		// var_dump($update_points);
		// var_dump($is_user_rebate_log);
		// var_dump($is_user_rebate_log);
		if ($update_points!==false and $is_save_user_moneylog!==false and $is_user_rebate_log!==false){ 
			$lastsave["lasttime"]=time();
			//$lastsave["next_num"]=$next_num+500;
			$is_last=M("user_rebate_set")->where("id=1")->save($lastsave);
			//插入赠送记录
			$rebate_send_log['send_num'] = $all_num;
			$rebate_send_log['send_all_money'] = $all_money;
			$rebate_send_log['send_money'] = $money;
			$rebate_send_log['send_time'] = NOW_TIME;
			$rebate_send_log['send_user'] = $all_user;
			$is_rebate_send_log=M("user_rebate_send_log")->add($rebate_send_log);
			if($is_last!==false and $is_rebate_send_log!==false){
				$Rebate->commit();
				G('end');
				echo '本次共成功发放红利：'.($all_money)."元，共".$all_num."个赠送权限"."，涉及".$all_user."人，执行时间：".G('begin','end').'秒,请不要关闭页面，等待继续执行，'.date("H:i:s",time()); 
				exit;
			}else{
				 $Rebate->rollback(); 
				 echo '红利发放失败,错误代码021'; 
			}
		}else{
			$Rebate->rollback(); 
			echo '红利发放失败,错误代码020';
		}
		exit;
	}	
}
function jason_sell_fanli(){
	echo "系统执行过程中清不要关闭页面！！！";
	$user_rebate_set=M("user_sell_rebate_set")->find();
	$star_times=strtotime(date('Y-m-d',time())." ".$user_rebate_set["open_time1"].":".$user_rebate_set["open_time2"]);
	if($star_times<time() and $user_rebate_set["status"]==1){
		G('begin');
		$is_fafang_time=strtotime(date('Y-m-d 00:00:01',time()));
		if($user_rebate_set["lasttime"]>$is_fafang_time){
			echo '红利发放完毕';  
			exit;   
		}
		$next_num=$user_rebate_set["next_num"];
		$Rebate=M("user_rebate");
		$Rebatelog=M("user_sell_rebate_log");
		$User=M("user");
		if($user_rebate_set["return_type"]==1){
			$money=$user_rebate_set["return_money"];
		}else{
			$map_today['sell_uid'] = array("neq",0);
			$amount_all=$amount_all==0?"0.00":$amount_all;
			$start=strtotime(date("Y/m/d", strtotime('-1 day'))." 00:00:01");
			$end=strtotime(date("Y/m/d", strtotime('-1 day'))." 23:59:59"); 
			$map_today['create_time'] =array('between',$start.','.$end);
			$map_today['sell_uid'] = array("neq",0);
			$amount_yesterday = model('order')->where($map_today)->sum('real_amount');
			$amount_yesterday=$amount_yesterday==0?"0.00":$amount_yesterday;
			$all_num=M("user")->sum("rebate_sell_num");
			$money=$amount_yesterday*0.01*$user_rebate_set["return_per"]/100/$all_num;
		}
		$return_type=$user_rebate_set["return_type"];
		if($money<0.01){
			echo '红利发放失败,错误代码098';  
			exit;   
		}
		$user_num=0;
		$all_num=0;//人数
		$Rebate->startTrans();
		$all_list=M("user u")->field("id,rebate_sell_num,old_rebate_sell_num,user_money,freeze_money,pay_points as return_money")->select();
		foreach($all_list as $key=>$val){
			if($val["rebate_sell_num"]>0){
				//更新账户信息
				$return_money=$val["rebate_sell_num"]*$money;
				$where['id']=$val["id"];
				$where['user_money']=array('exp','user_money+'.$return_money);
				$where['pay_points']=array('exp','pay_points+'.$return_money);
				$all_return=$val["return_money"]+$return_money;
				$all_num_over=floor($all_return/5000);
				if($all_num_over>$val["old_rebate_sell_num"]){
					$last_num=bcsub($all_num_over,$val["old_rebate_sell_num"],0);
					$where['old_rebate_sell_num']=array('exp','old_rebate_sell_num+'.$last_num);
					$where['rebate_sell_num']=array('exp','rebate_sell_num-'.$last_num);
					$rebate_log['user_id'] = $val["id"];
					$rebate_log['save_num'] = $last_num;
					$rebate_log['msg'] = "赠送金额满足条件取消".$last_num."个赠送权";
					$rebate_log['add_time'] = NOW_TIME;
					$rebate_log['type'] = 2;
					$rebate_log['rebate_num'] = bcsub($val["rebate_sell_num"],$last_num,0);
					$rebate_log['old_rebate_num'] = $val["old_rebate_sell_num"]+$last_num;
					$rebate_log_arr[]=$rebate_log;
					unset($rebate_log);
				}
				$save_money_arr[]=serialize($where);
				unset($where);
				//插入资金变动记录
				$user_money['user_id'] = $val["id"];
				$user_money['money'] = $return_money;
				$user_money['msg'] = "商家赠送发放";
				$user_money['info']="赠送发放：".$return_money."元 X ".$val["rebate_sell_num"]."个赠送权";
				$user_money['dateline'] = NOW_TIME;
				$user_money['type'] = 11;
				$user_money['user_money'] = $val["user_money"]+$return_money;
				$user_money['freeze_money'] = $val["freeze_money"];
				$user_money['pay_points'] =$val["return_money"]+$return_money;
				$user_moneylog[]=$user_money;
				$all_money+=$return_money;// 总金额
				$all_num+=$val["rebate_sell_num"]; //总赠送权数量
				$all_user+=1;//总用户数
				unset($user_money);
				unset($return_money);
				unset($last_num);
			}
		}
		if(count($save_money_arr)>0){
			foreach($save_money_arr as $valc){
				$valc=unserialize($valc);
				$update_points=$User->save($valc);
				if($update_points === false ){$update_points=false;continue;}
			}
		}else{
			$update_points=true;    
		}
		if(count($user_moneylog)>0){
			$is_save_user_moneylog=model('User_moneylog')->addAll($user_moneylog);//更新资金记录
		}else{
			$is_user_rebate_log=true;
		}
		if(count($rebate_log_arr)>0){
			$is_user_rebate_log=M('user_sell_rebate_log')->addAll($rebate_log_arr);//更新赠送权记录
		}else{
			$is_user_rebate_log=true;
		}
		if ($update_points!==false and $is_save_user_moneylog!==false and $is_user_rebate_log!==false){ 
			$lastsave["lasttime"]=time();
			//$lastsave["next_num"]=$next_num+500;
			$is_last=M("user_sell_rebate_set")->where("id=1")->save($lastsave);
			//插入赠送记录
			$rebate_send_log['send_num'] = $all_num;
			$rebate_send_log['send_all_money'] = $all_money;
			$rebate_send_log['send_money'] = $money;
			$rebate_send_log['send_time'] = NOW_TIME;
			$rebate_send_log['send_user'] = $all_user;
			$is_rebate_send_log=M("user_sell_rebate_send_log")->add($rebate_send_log);
			if($is_last!==false and $is_rebate_send_log!==false){
				$Rebate->commit();
				G('end');
				echo '本次共成功发放红利：'.($all_money)."元，共".$all_num."个赠送权限"."，涉及".$all_user."人，执行时间：".G('begin','end').'秒,请不要关闭页面，等待继续执行，'.date("H:i:s",time()); 
				exit;
			}else{
				 $Rebate->rollback(); 
				 echo '红利发放失败,错误代码021'; 
			}
		}else{
			$Rebate->rollback(); 
			echo '红利发放失败,错误代码020';
		}
		exit;
	}	
}